<?php
namespace app\api\controller\deerhome\worker;

use app\api\controller\deerhome\worker\BaseAuth;
use think\Db;
use think\Validate;

/**
 * 我的任务
 */
class Task extends BaseAuth
{
    private function timeCreat($day){
        $timeArr=[];
        //从8点开始到22点，每隔半个小时生成一个元素
        for($i=8;$i<=22;$i++){
            $time1=str_pad($i,2,"0",STR_PAD_LEFT).":00";
            $time2=str_pad($i,2,"0",STR_PAD_LEFT).":30";
            //c=1表示已经约满
            $timeArr[]=$time1;
            $timeArr[]=$time2;
        }
        //取出时间段配置
        $config=$this->getConfig("sys");
        $time_start=(int)\str_replace(":","",$config['time_start']);
        $time_end=(int)\str_replace(":","",$config['time_end']);
        foreach($timeArr as $k=>&$v){
            $time=(int)\str_replace(":","",$v);
            if($time<$time_start || $time>$time_end){
                unset($timeArr[$k]);
            }
        }
        $timeArr=array_values($timeArr);
        return $timeArr;
    }
    /**
     * 获取时间列表
    */
    public function get_time()
    {
        $out=[];
        $out['timeDay']=[];
        //获取最近15天的日期
        for($i=0;$i<15;$i++){
            $out['timeDay'][$i]['v']=date("Y-m-d",strtotime("+$i day"));
            $out['timeDay'][$i]['n']=$this->getWeek(date("Y-m-d",strtotime("+$i day")));
        }
        $out['timeTime']=$this->timeCreat(date("Y-m-d",strtotime("+1 day")));
        $this->ok($out);
    }
    /**
     * 修改预约时间
    */
    public function edit_time()
    {
        $day=$this->request->param("day","");
        $time=$this->request->param("time","");
        $sn=$this->request->param("sn","",'trim');
        if(!preg_match("/^\d{4}-\d{2}-\d{2}$/",$day)){
            $this->err("日期格式不正确",1);
        }
        if(!preg_match("/^\d{2}:\d{2}$/",$time)){
            $this->err("时间格式不正确",1);
        }
        $dayTime=$day." ".$time .":00";
        if($dayTime<=date("Y-m-d H:i:s")){
            $this->err("预约时间不能小于当前时间",1);
        }
        $order=Db::name("deerhome_order")->where("sn",$sn)->where("worker_id",$this->_user['id'])->where("status","in",[3,4])->find();
        if(!$order){
            $this->err("订单不存在或者状态已发生改变",1);
        }
        Db::startTrans();
        try{
            Db::name("deerhome_order")->where("id",$order['id'])->update([
                "date_day"=>$day,
                "date_time"=>$time
            ]);
            Db::name("deerhome_order_log")->insert([
                'order_id'=>$order['id'],
                'add_time'=>date("Y-m-d H:i:s"),
                'ac_user'=>'服务人员:'.$this->_user['uname'],
                'note'=>"修改预约时间为{$day} {$time}"
            ]);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage());
        }
        try{
            //通知用户
            \Tools\Msg::toUserEditTime($order['jz_user_id'],$order['sn'],$dayTime);
        }catch(\Exception $e){
        }
        $this->ok();
    }
    /**
     * 数量统计
    */
    public function count_num()
    {
        $count=Db::name("deerhome_order")->where("worker_id",$this->_user['id'])->where("status","in",[3,4])->count();
        $this->ok($count);
    }
    /**
     * 订单完成
    */
    public function done()
    {
        $sn=$this->request->param("sn","",'trim');
        $worker_last_price=$this->request->param("price",0,'floatval');
        $worker_imgs=$this->request->param("imgs/a",[]);
        $worker_note=$this->request->param("note","",'trim');
        $order=Db::name("deerhome_order")->where("sn",$sn)->where("worker_id",$this->_user['id'])->where("status",3)->find();
        if(!$order){
            $this->err("订单不存在或者状态已发生改变");
        }
        if($worker_last_price<0){
            $this->err("价格不能小于0");
        }
        $arr=[];
        $arr['status']=4;
        $arr['worker_apply_time']=date("Y-m-d H:i:s");
        $arr['worker_last_price']=$worker_last_price;
        $arr['worker_note']=$worker_note;
        if(count($worker_imgs)>0){
            $arr['worker_imgs']=implode(",",$worker_imgs);
        }
        
        $arr['price_bcj']=\bcadd($order['price_bcj'],$worker_last_price,2);
        $arr['price_total']=\bcadd($order['price_total'],$worker_last_price,2);
        $arr['price_need_pay']=\bcadd($order['price_need_pay'],$worker_last_price,2);

        //会员折扣，计算折扣前的价格
        $arr['price_discount']=\bcadd($order['price_discount'],$worker_last_price,2);
        $worker_last_price_discount=$worker_last_price;
        if(bccomp($order['price_discount_bl'],1,2)<0){
            $worker_last_price_discount=bcdiv($worker_last_price,$order['price_discount_bl'],2);
            $arr['price_bcj']=\bcadd($order['price_bcj'],$worker_last_price_discount,2);
            $arr['price_total']=\bcadd($order['price_total'],$worker_last_price_discount,2);
            $arr['price_discount']=\bcadd($order['price_discount'],$worker_last_price,2);
            $arr['price_need_pay']=\bcadd($order['price_need_pay'],$worker_last_price,2);
        }
        //计算分成
        $items=Db::name("deerhome_items")->field("price,worker_fc_bl")->where("id",$order['jz_items_id'])->find();
        if(!$items){
            $this->err("服务项目已被删除");
        }

        $worker_price_base=\bcmul($arr['price_need_pay'],$items['worker_fc_bl']/100,2);
        $arr['worker_price']=$worker_price_base;
        $arr['worker_price_note']="按交易额的{$items['worker_fc_bl']}%分成";
        //判断是否有额外分成
        $fc=Db::name("deerhome_worker_lev")->where("fybl",">",0)->where("id",$this->_user['jz_worker_lev_id'])->find();
        if($fc){
            $award=\bcmul($arr['price_need_pay'],$fc['fybl']/100,2);
            $arr['worker_price']=\bcadd($arr['worker_price'],$award,2);
            $arr['worker_price_note']="基本分成(按交易额{$items['worker_fc_bl']}%)￥{$worker_price_base}元，等级{$fc['name']}，额外奖励({$fc['fybl']}%)￥{$award}元";
        }
        Db::startTrans();
        try{
            Db::name("deerhome_order")->where("id",$order['id'])->update($arr);
            Db::name("deerhome_order_log")->insert([
                'order_id'=>$order['id'],
                'add_time'=>date("Y-m-d H:i:s"),
                'ac_user'=>'服务人员:'.$this->_user['uname'],
                'note'=>"服务完成，请您验收".($worker_last_price>0?"并支付尾款":"")
            ]);
            if($worker_last_price>0){
                Db::name("deerhome_order_pay_log")->insert([
                    'deerhome_user_id'=>$order['jz_user_id'],
                    'order_sn'=>$order['sn'],
                    'payway_type'=>1,
                    'price'=>$worker_last_price,
                    'note'=>"补差价".($order['price_discount_bl']<1?"，原价￥{$worker_last_price_discount}，会员折后￥{$worker_last_price}":""),
                    "add_time"=>date("Y-m-d H:i:s")
                ]);
            }
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage());
        }
        $this->ok();
    }
    /**
     * 放弃订单
    */
    public function giveup()
    {
        $sn=$this->request->param("sn","",'trim');
        $order=Db::name("deerhome_order")->where("sn",$sn)->where("worker_id",$this->_user['id'])->where("status","in",[3,4])->find();
        if(!$order){
            $this->err("订单不存在或者状态已发生改变");
        }
        $arr=[];
        $arr['status']=2;
        $arr['worker_id']=0;
        $arr['worker_get_time']=Db::raw("null");
        $arr['worker_name']="";
        $arr['worker_price']=0;
        $arr['worker_price_note']="";
        Db::startTrans();
        try{
            Db::name("deerhome_order")->where("id",$order['id'])->update($arr);
            Db::name("deerhome_order_log")->insert([
                'order_id'=>$order['id'],
                'add_time'=>date("Y-m-d H:i:s"),
                'ac_user'=>'服务人员:'.$this->_user['uname'],
                'note'=>"{$this->_user['uname']}放弃服务，将为您重新派单"
            ]);
            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            $this->err($e->getMessage());
        }
        $this->ok();
    }
    public function index()
    {
        $latitude=$this->request->param("latitude",0,'floatval');
        $longitude=$this->request->param("longitude",0,'floatval');
        $cate=$this->request->param("cate",0,'intval');
        $sn=$this->request->param("sn","",'trim');
        $key=$this->request->param("key","",'trim');
        $type=$this->request->param("type","",'trim');

        $where=[];
        if($cate==0){
            $where['o.status']=['in',[3,4]];
        }
        if($cate==1){
            $where['o.status']=5;
        }
        if($cate==2){
            $where['o.status']=['in',[6,7,8]];
        }
        if($sn){
            $where['o.sn']=$sn;
        }
        if($key!=""){
            $where['o.item_name|o.item_gg_name|o.user_name|o.user_phone']=['like',"%{$key}%"];
        }

        if($type=="log"){
            $where=[];
            if($cate==1){
                $where['o.status']=['in',[3,4,5]];
                $where['o.worker_price_to_wallet']=0;
            }
            if($cate==2){
                $where['o.status']=5;
                $where['o.worker_price_to_wallet']=1;
            }
        }


        $where['o.worker_id']=$this->_user['id'];
        $out=Db::name("deerhome_order")
        ->alias("o")
        ->join("deerhome_items i","i.id=o.jz_items_id","left")
        ->join("deerhome_cate c","c.id=i.cate_id","left")
        ->field("o.sn,o.status,o.user_name,o.user_phone,o.item_name as item,o.item_gg_name as item_gg,o.num as item_gg_num,o.price_need_pay,o.price_payed,o.worker_price,o.worker_price_note,o.worker_price_to_wallet,o.address_title,o.address_address,o.address_detail,o.latitude,o.longitude,o.date_day,o.date_time,o.note,o.imgs,c.name as title,c.face_image")
        ->where($where)
        ->order("o.worker_get_time desc")
        ->paginate(5,false)->toArray();

        foreach($out['data'] as &$v){
            $v['cate_img']=$this->fixImg($v['face_image']);
            $v['price']="￥".$v['price_need_pay'];
            $v['price_left']=\bcsub($v['price_need_pay'],$v['price_payed'],2);
            $v['address']=[];
            $v['address']['km']="";
            if($latitude>0 && $longitude>0){
                $v['address']['km']=$this->getKm($latitude,$longitude,$v['latitude'],$v['longitude'])."km";
            }
            $v['address']['title']=$v['address_title']." ".$v['address_detail'];
            $v['address']['detail']=$v['address_address'];
            $v['address']['latitude']=(float)$v['latitude'];
            $v['address']['longitude']=(float)$v['longitude'];
            $v['date']=[];
            $v['date']['time']=$v['date_day']." ".$v['date_time'];
            $v['date']['time_tip']=$v['date_day']==date("Y-m-d")?"今天":"";
            $v['date']['light']=$v['date_time']>="18:00"?"夜间":"";
            $week=$this->getWeek($v['date_day']);
            if(\substr($v['date']['time'],0,4)==date("Y")){
                $v['date']['time']=$week ." ". \date("m月d日 H:i",strtotime($v['date']['time']));
            }else{
                $v['date']['time']=\date("Y年m月d日 H:i",strtotime($v['date']['time']));
            }

            $v['imgs']=explode(",",$v['imgs']);
            $v['imgs']=array_filter($v['imgs']);

            $v['user']=[];
            $v['user']['name']=$v['user_name'];
            $v['user']['tel']=$v['user_phone'];
            $v['user']['tel_mask']=substr($v['user_phone'],0,3)."****".substr($v['user_phone'],7,4);

            unset($v['user_name']);
            unset($v['user_phone']);
            unset($v['date_day']);
            unset($v['date_time']);
            unset($v['address_title']);
            unset($v['address_address']);
            unset($v['latitude']);
            unset($v['longitude']);
            unset($v['price_need_pay']);
            unset($v['face_image']);
        }
        $this->ok($out);
    }
    /**
     * 计算2个坐标的距离
    */
    private function getKm($latitude1, $longitude1, $latitude2, $longitude2)
    {
        $earthRadius = 6378138; //approximate radius of earth in meters

        $lat1 = ($latitude1 * pi() ) / 180;
        $lng1 = ($longitude1 * pi() ) / 180;

        $lat2 = ($latitude2 * pi() ) / 180;
        $lng2 = ($longitude2 * pi() ) / 180;

        $calcLongitude = $lng2 - $lng1;
        $calcLatitude = $lat2 - $lat1;
        $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
        $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
        $calculatedDistance = $earthRadius * $stepTwo;

        return round($calculatedDistance/1000,2);
    }
}
